"use strict";

import Vue from 'vue';
import axios from "axios";
import store from '@/store/index';
import router from '@/router/index';
import Qs from 'qs';

// Full config:  https://github.com/axios/axios#request-config
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? '' : "https://yanfa.shequyun.cn";
// axios.defaults.headers.common['token'] = store.state.token;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data
    return Qs.stringify(data);
  }]
};

const errorCode = function (code, message) {
  switch (code) {
    // 401: 未登录
    // 未登录则跳转登录页面，并携带当前页面的路径
    // 在登录成功后返回当前页面，这一步需要在登录页操作。                
    case 401:
      router.replace({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      });
      break;

    // 403 token过期
    // 登录过期对用户进行提示
    // 清除本地token和清空vuex中token对象
    // 跳转登录页面                
    case 90005:
      Vue.prototype.$Message.error(message)
      // 清除token
      localStorage.removeItem('token');
      store.commit('setToken', null);
      // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面 
      setTimeout(() => {
        router.replace({
          path: '/login',
          query: {
            redirect: router.currentRoute.fullPath
          }
        });
      }, 1000);
      break;

    // 404请求不存在
    case 404:
      Vue.prototype.$Message.error(message);
      break;

    // 500请求异常
    case 500:
      Vue.prototype.$Message.error(message);
      break;

    // 其他错误，直接抛出错误提示
    default:
      // Vue.prototype.$Message.error(message);
  }
}

const _axios = axios.create(config);

_axios.interceptors.request.use(
  config => {
    if (store.state.token) {
      config.headers.common.token = store.state.token
    }
    // Do something before request is sent
    return config
  },
  error => {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  response => {
    // Do something with response data
    if (!response.data.isSucceed) {
      // Do something with response error
      if (response.data.code != undefined){
        errorCode(response.data.code, response.data.message)
      }
    }
    return response;
  },
  error => {
    errorCode(response.data.code, response.data.message)
    return Promise.reject(error);
  }
);

Plugin.install = function (Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  window.$axios = axios
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;
